package br.com.usjt.tcc.schedule.jpa.dao;

import java.util.Iterator;
import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.usjt.tcc.schedule.interfaces.dao.AnnouncementDao;
import br.com.usjt.tcc.schedule.model.Announcement;

@RequestScoped
public class JpaAnnouncementDao implements AnnouncementDao {

	@Inject
	private EntityManager entityManager;

	public JpaAnnouncementDao() {
	}

	public JpaAnnouncementDao(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public void adiciona(Announcement announcement) {
		entityManager.persist(announcement);
	}

	public void atualiza(Announcement announcement) {
		entityManager.merge(announcement);
	}

	@SuppressWarnings("unchecked")
	public List<Announcement> lista() {
		Query query = entityManager.createQuery("select a from Announcement a");
		return query.getResultList();
	}

	public Announcement busca(Long id) {
		return entityManager.find(Announcement.class, id);
	}

	@Override
	public void adiciona(List<Announcement> announcements) {
		Iterator<Announcement> iterator = announcements.iterator();
		while (iterator.hasNext()) {
			Announcement announcement = (Announcement) iterator.next();
			entityManager.persist(announcement);
		}
	}
}
